package org.coco.mybatis.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MapperProxy implements InvocationHandler {

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //查看该方法是属于哪一个接口下的方法
        Class<?> clazz = method.getDeclaringClass();
        //获取到该方法的名称
        String name = method.getName();
        MapperMethod mapperMethod = new MapperMethod();
        return mapperMethod.execute(method,clazz.getName(),name,args);
    }

    public static <T> T newMapperProxy(Class<T> mapperInterface) {
        ClassLoader classLoader = mapperInterface.getClassLoader();
        Class<?>[] interfaces = new Class[]{mapperInterface};
        MapperProxy proxy = new MapperProxy();
        return (T) Proxy.newProxyInstance(classLoader, interfaces, proxy);
    }
}
